//
//  PulishMainViewController.m
//  House
//
//  Created by 吕品 on 16/5/31.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "PulishMainViewController.h"
#import "AgentDetailModel.h"
#import "AgentDetailViewController.h"
#import "AgentListModel.h"
#import "House-Swift.h"
#import <YTKKeyValueStore/YTKKeyValueStore.h>
@interface PulishMainViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, copy) NSArray *areaArray;
@property (nonatomic, copy) NSArray *dataArray;
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTabelView;
@property (nonatomic, strong) UISearchBar *bar;
@end

@implementation PulishMainViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self fetchAreaArray];
    [self fetchDataInfo];
}
- (void)reloadData {
    [_leftTableView reloadData];
    [_rightTabelView reloadData];
}
- (void)fetchDataInfo {
//    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:20 weight:20], NSForegroundColorAttributeName: [UIColor whiteColor]};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.animationType = MBProgressHUDAnimationZoomIn;
    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleBlur;
    hud.backgroundView.backgroundColor = [UIColor whiteColor];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = @"数据加载中~";
    [NetRequest getInformationWithGetMethodWithUrl:[NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/api.php/Jiamengshang/index/areaid/%@", [UserInfoManager sharedManager].userCityID] success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]] ) {
            if ([[responseObject[@"flag"] description] isEqualToString:@"0"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    hud.label.text = @"获取失败";
                    [hud hideAnimated:YES afterDelay:1];
                });
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES afterDelay:1];
                });
                NSArray *arr = responseObject[@"jiamengshang"];
                NSArray *jiamengshangArr = [AgentListModel setValuesAndKeysWithArray:arr];
                NSMutableArray *dataArray = [NSMutableArray array];
                for (NSDictionary *dic in _areaArray) {
                    NSMutableArray *tempArray = [NSMutableArray array];
                    for (PublishMainRightCellModel *model in jiamengshangArr) {
                        if ([model.areaid.description isEqualToString:[dic[@"areaid"] description]]) {
                            [tempArray addObject:model];
                        }
                    }
                    [dataArray addObject:tempArray];
                }
                _dataArray = dataArray.copy;
                [self reloadData];
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

//获取区域数组
- (void)fetchAreaArray {

//    self.areaArray = [AreaInforManager getArrayWith:dataBaseName tableName:tableName cityID:[UserInfoManager sharedManager].userCityID];
    //    [self reloadData];
    [NetRequest getInformationWithGetMethodWithUrl:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/qu" success:^(NSURLSessionDataTask *task, id responseObject) {
        self.areaArray = responseObject;
        [self reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}

- (void)initUI {
    [self initSearchBar];
    [self initTableView];//初始化tableview
}

- (void)initSearchBar {

    UIView *naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    [self.view addSubview:naviView];
    naviView.backgroundColor = KNaviBackColor;


    self.bar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 40, 50)];
    _bar.center = CGPointMake(naviView.center.x, naviView.center.y + 5);
    [naviView addSubview:_bar];
    _bar.barStyle = UISearchBarStyleDefault;
    _bar.backgroundColor = [UIColor clearColor];
    [_bar.subviews.firstObject.subviews.firstObject removeFromSuperview];
    for (UIView *view in _bar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
        }
    }
    _bar.placeholder = @"请输入门店名称";
    _bar.delegate = self;

}

- (void)initTableView{
    //letf
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:_leftTableView];
    UIView *superView = self.view;
    CGFloat width = self.view.mj_w / 3.0;
    [_leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.mas_equalTo(superView.mas_left);
        make.bottom.mas_equalTo(superView).with.offset(-44);
        make.width.mas_equalTo(width);
    }];
    _leftTableView.dataSource = self;
    _leftTableView.delegate = self;
    _leftTableView.tableFooterView = [UIView new];
    [_leftTableView registerClass:[PublishMainLeftTableViewCell class] forCellReuseIdentifier:NSStringFromClass([PublishMainLeftTableViewCell class])];
    //right
    self.rightTabelView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:_rightTabelView];
    [_rightTabelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.mas_equalTo(_leftTableView);
        make.right.mas_equalTo(superView.mas_right);
        make.left.mas_equalTo(_leftTableView.mas_right);
        make.width.mas_equalTo(width * 2);
    }];
    _rightTabelView.dataSource = self;
    _rightTabelView.delegate = self;
    _rightTabelView.tableFooterView = [UIView new];
    [_rightTabelView registerClass:[PublishMainRightTableViewCell class] forCellReuseIdentifier:NSStringFromClass([PublishMainRightTableViewCell class])];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_leftTableView]) {
        return 1;
    } else {
        return _areaArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_leftTableView]) {
        return _areaArray.count;
    } else {
        return [_dataArray[section] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {
        PublishMainLeftTableViewCell *leftCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PublishMainLeftTableViewCell class])];
        NSDictionary *dic = _areaArray[indexPath.row];
        leftCell.label.text = dic[@"areaname"];
        return leftCell;
    } else {
        PublishMainRightTableViewCell *rightCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PublishMainRightTableViewCell class])];
        AgentListModel *model = _dataArray[indexPath.section][indexPath.row];
        if (model) {
            rightCell.nameLabel.text = model.company.description;
            rightCell.addressLabel.text = model.addr.description;
            rightCell.telLabel.text = model.mobile.description;
        }
        return rightCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {
        return 44;
    } else {
        return 100;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_leftTableView]) {
        return 0;
    } else {
        return 20;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_rightTabelView]) {
        NSDictionary *dic = _areaArray[section];
        return dic[@"areaname"];
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_leftTableView]) {

        if ([_dataArray[indexPath.row] count] != 0) {
            [_rightTabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    } else {
        AgentDetailViewController *detailVC = [[AgentDetailViewController alloc] init];
        [self.navigationController pushViewController:detailVC animated:YES];
        detailVC.type = Community;
        detailVC.tabbarHidden = YES;
        AgentListModel *model = _dataArray[indexPath.section][indexPath.row];
        detailVC.model = model;
        self.tabBarController.hidesBottomBarWhenPushed = YES;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isEqual:_rightTabelView]) {
        NSIndexPath *index = [_rightTabelView indexPathForCell:_rightTabelView.visibleCells.firstObject];
        [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index.section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_bar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = @"搜索中";
    [NetRequest getInformationWithGetMethodWithUrl:[NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/api.php/Jiamengshang/xiangqing/company/%@", [searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]] success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        if ([[responseObject[@"flag"] description] isEqualToString:@"1"]) {
            hud.label.text = @"搜索成功";
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
            });
            AgentListModel *model = [AgentListModel modelWithDic:responseObject[@"ziyuan"]];
            AgentDetailViewController *detailVC = [[AgentDetailViewController alloc] init];
            detailVC.model = model;
            detailVC.type = Community;
            [self.navigationController pushViewController:detailVC animated:YES];
            detailVC.tabbarHidden = YES;
        } else {
            hud.label.text = @"未找到结果";
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES afterDelay:1.0];
            });
        }
        [searchBar resignFirstResponder];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"社区门店";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self initUI];//初始化UI
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
